<?php
declare (strict_types = 1);
namespace app\mini\controller;

use app\BaseController;
use app\mini\model\MiniProgramFans;
use think\facade\Cache;


/*
 *小程序验证基类
 */
class Access extends BaseController
{
  protected  $customerId;
  protected  $fansId;
  protected  $fansInfo;
  protected  $sessionKey;
  protected  $openId;
  protected  $token;

  protected $middleware = ['MiniProgramAccess'];
  public function initialize()
  {
    parent::initialize();
    $this->handleInit();
  }

  protected function handleInit()
  {
    $token = $this->request->param('token');
    if( empty($token) ){
      $token = $this->request->header('token','');
    }
    $this->request->token = $this->token = $token;
    $this->request->verifyTokenRes = $verifyTokenRes = \app\Jwt::verifyToken($this->token);
    if( $verifyTokenRes ){
      $this->request->fansId = $this->fansId = $verifyTokenRes['private']['fansId'];
      $this->request->fansInfo = $this->fansInfo = $this->getFansInfo();
      $this->request->customerId = $this->customerId = $this->fansInfo['customerId']??0;
      $this->openId = $this->fansInfo['openId']??'';
      $this->sessionKey = $this->fansInfo['sessionKey']??'';
//      $this->agentId =env('weChat.AgentId','');
//      $this->Secret =env('weChat.Secret','');
//      $this->corpid =env('weChat.corpid','');
    }
  }

  /*获取粉丝缓存信息*/
  protected function getFansInfo(): Array
  {
    $info =  Cache::get('mfans:MiniProgram-'.$this->fansId);

    if( empty($info) ){
      $info = MiniProgramFans::where('id','=',$this->fansId)
                    ->field('id as fansId,openId,nickName,gender,city,province,country,avatarUrl,customerId,telephone')
                    ->find();
      if( is_null($info) ){
        $info = [];
      }else{
        $info = $info->toArray();
      }
      $scode = ''; // 初始化签约码
      if( $info['customerId'] != 0 ){
        $scode = \app\crm\model\Customer::where('customer_id','=',$info['customerId'])->value('sign_up_number','');
      }
      $info['scode'] = $scode;
      $info['token'] = $this->token;
      Cache::set('mfans:MiniProgram-'.$this->fansId,$info);
    }
    return $info;
  }




}
